/*
 * UsuarioDAO.java
 *
 * Created on 14 de Maio de 2007, 06:30
 *
 */

package net.sf.jOpinionPoll.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import net.sf.jOpinionPoll.dao.UsuarioDao;
import net.sf.jOpinionPoll.entity.Usuario;

/**
 *
 * @author erico
 */
public class UsuarioDaoJpa extends DaoJpa implements UsuarioDao {
    
    /** Creates a new instance of Entidade */
    public UsuarioDaoJpa() {
    }
    
    private DaoJpaHelper<Usuario> getDaoJpaHelper() {
    	return new DaoJpaHelper<Usuario>(getEntityManager(), Usuario.class);
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public Usuario findFetchByPk(Object id) {
        EntityManager em = getEntityManager();
        Query q;
        q = em.createNamedQuery("Usuario.fetch.findById");
        q.setParameter("id", id);
        
        List<Usuario> u = (List<Usuario>)q.getResultList();

        return u.size() > 0 ? u.get(0) : null;
    }
    
    @Override
    public boolean existsEmail(String email) {
        EntityManager em = getEntityManager();

        Query query = em.createQuery("select count(o) from Usuario as o where o.email = :email");
        query.setParameter("email", email);
        return (((Long)query.getSingleResult()) > 0);
    }
    
    @Override
    public boolean existsCPFCNPJ(String cpfcnpj) {
        EntityManager em = getEntityManager();

        Query query = em.createQuery("select count(o) from Usuario as o where o.cpfcnpj = :cpfcnpj");
        query.setParameter("cpfcnpj", cpfcnpj);
        return (((Long)query.getSingleResult()) > 0);
    }

	@Override
	public void add(Usuario newInstance) {
		getDaoJpaHelper().add(newInstance);
	}

	@Override
	public int count() {
		return getDaoJpaHelper().count();
	}

	@Override
	public List<Usuario> list(int firstResult, int maxResults) {
		return getDaoJpaHelper().list(firstResult, maxResults);
	}

	@Override
	public void remove(Usuario cliente) {
		getDaoJpaHelper().remove(cliente);
	}

	@Override
	public void set(Usuario cliente) {
		getDaoJpaHelper().set(cliente);
	}
}